package org.Demo;

import org.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertDemo {
    public static void main(String[] args) {
        //定义数据库操作相关变量
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            //获取用户输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入学号:");
            String sn = scanner.next();
            System.out.println("请输入姓名:");
            String name = scanner.next();
            System.out.println("请输入邮箱:");
            String qq_mail = scanner.next();
            System.out.println("请输入班级编号:");
            int classes_id = scanner.nextInt();

            //获取数据库连接
            connection = DBUtil.getConnection();

            //构造sql语句
            String sql = "insert into student (sn, name, qq_mail, classes_id) values(?,?,?,?)";

            //获取预处理对象
            preparedStatement = connection.prepareStatement(sql);

            //把占位符替换真实值
            preparedStatement.setString(1,sn);
            preparedStatement.setString(2,name);
            preparedStatement.setString(3,qq_mail);
            preparedStatement.setInt(4,classes_id);

            //执行sql并获取结果
            int i = preparedStatement.executeUpdate();
            if (i > 0){
                System.out.println("录入学生信息成功");
            } else {
                System.out.println("执行失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源
            DBUtil.close(null, preparedStatement, connection);
        }
    }
}
